import { isObject, isArray } from '@/utils/is';

/**
 * 对象与数组的深拷贝 
 * @param {object | Array} src 返回的对象或数组
 * @param {object | array} target 需要拷贝的对象或数组
 * @returns {string} 返回src
 */
export function deepMerge<T = any>(src: any = {}, target: any = {}): T {
    let key: string;
    for (key in target) {
        if (isObject(target[key])) {
            src[key] = deepMerge(src[key], target[key])
        } else if (isArray(target[key])) {
            let list: any = []
            for (let i = 0; i < target[key].length; i++) {
                list.push(target[key][i])
            }
            src[key] = list
        } else {
            src[key] = target[key]
        }
    }
    return src;
}
export function setObjToUrlParams(baseUrl: string, obj: any): string {
    let parameters = '';
    for (const key in obj) {
        parameters += key + '=' + encodeURIComponent(obj[key]) + '&';
    }
    parameters = parameters.replace(/&$/, '');
    return /\?$/.test(baseUrl) ? baseUrl + parameters : baseUrl.replace(/\/?$/, '?') + parameters;
}

export function setHttpFormData(obj: object): FormData {
    let form = new FormData();
    let key: string, value: string;
    for ([key, value] of Object.entries(obj)) {
        if (value === null) {
            value = ''
        }
        if (isObject(value) || isArray(value)) {
            form.append(key, JSON.stringify(value))
        } else {
            form.append(key, value)
        }
    }
    return form
}